import React, { useEffect, useState } from "react";
import { Button, Form, Input, message } from "antd";
import style from "./login.module.scss";
import initBackground from "./init.ts";
// 引入请求api
import api from "@/api";
// 引入跳转路由的hooks
import { useNavigate } from "react-router-dom";
import login from "../../api/login";
import { getUser, loginCkgl } from "../../api/ckgl";

export default function index() {
  let navigate = useNavigate();
  // 点击登录按钮
  const onFinish = async (values: any) => {
    let { email, password } = values;
    // 获取验证码参数

    // admin(系统管理员)，purchaser（采购人员），m-admin（物资管理员），picker（领物），visitor（游客）
    // localStorage.role_code = "admin";
    // let res = await api.login.fixLogin(data);
    // localStorage.setItem("react-jwt-token", "test");
    let res: any = await loginCkgl({
      email,
      password,
      // email: "123@qq.com",
      // password: password as string,
    });
    console.log("res.data", res.data, res);
    const { token, user_id, role_code } = res.data;

    if (res.code !== 0) return message.warning("登录失败");
    localStorage.setItem("role_code", role_code);
    localStorage.setItem("token", token);
    localStorage.setItem("react-jwt-token", token);
    localStorage.setItem("user_id", user_id);
    getUser({
      user_id,
    }).then((res: any) => {
      const { username } = res.data;
      localStorage.setItem("username", username);

      message.success("登录成功");
      navigate("/home");
      window.location.reload();
    });

    // 使用 replace 方法
    // navigate.replace("/home");

    // token: string;
    // //  @int32
    // user_id: number;
    // // admin(系统管理员)，purchaser（采购人员），m-admin（物资管理员），picker（领物），visitor（游客）
    // role_code: string;
    // localStorage.setItem("react-jwt-token", res.data.token);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("失败了");
  };

  // 加载完这个组件之后，加载背景,获取验证码
  useEffect(() => {
    initBackground();
    window.onresize = function () {
      initBackground();
    };
  }, []);

  return (
    <div className={style.box}>
      {/* 存放背景 */}

      <div className={style.login}>
        <h1
          style={{
            color: "white",
            fontWeight: "bold",
            fontFamily: "微软雅黑",
            textAlign: "center",
            fontSize: "40px",
          }}
        >
          高校物资仓储管理系统
        </h1>
        <Form
          name="basic"
          wrapperCol={{ span: 24 }}
          // initialValues={{ email: "admin@qq.com", password: "123456789" }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            name="email" // 将 name 更新为 "email"
            rules={[
              { required: true, message: "请输入邮箱", whitespace: true },
              { type: "email", message: "请输入有效的邮箱地址" }, // 可选：添加电子邮件验证规则
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: "请输入密码", whitespace: true },
            ]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>

          <Form.Item wrapperCol={{ span: 24 }}>
            <Button htmlType="submit" type="primary" style={{ width: "100%" }}>
              登陆
            </Button>

            <Button
              style={{ width: "100%", marginTop: 18 }}
              onClick={() => navigate("/register")}
            >
              前往注册
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}
